package com.quark.framework.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.quark.framework.utility.QuarkLog;

public class QuarkDBPooledConnection {
	private int refCount = 0;
	private Connection connection = null;
	private Map<String, PreparedStatement> mapping = new HashMap<String, PreparedStatement>();
	//private ObjectPool stmPool = new GenericObjectPool();
	public QuarkDBPooledConnection(Connection c)
	{
		connection = c;
	}
	
	
	public void addRef()
	{
		refCount ++;
	}
	
	public void decRef()
	{
		refCount --;
	}
	
	protected void clearRef()
	{
		refCount = 0;
	}
	
	public void setConnection(Connection c)
	{
		connection = c;		
	}
	
	public boolean checkConnection()
	{
		try {
			return !connection.isClosed();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			QuarkLog.log(e);
			return false;
		}
	}
	public int getRefCount()
	{
		return refCount;
	}
	
	public Connection getConnection()
	{
		return connection;
	}
	
	public boolean isUsing()
	{
		return refCount > 0;
	}
	
	public boolean isSameConnection(Connection c)
	{
		return connection.equals(c);
	}
	
	public PreparedStatement getStatement(String key)
	{
		return mapping.get(key);
	}
	
	public void setPreparedStatement(String key, PreparedStatement ps)
	{
		mapping.put(key, ps);
	}
	
	public Statement getStatement()
	//FIXME:Need a pool here?
	{
		try
		{
			return connection.createStatement();
		}
		catch(Exception e)
		{
			QuarkLog.log(e);
			return null;
		}
	}
	
	public void returnStatement(Statement stm)
	//FIXME: POOL IT
	{
		try
		{
			stm.close();
		}catch(Exception e)
		{
			QuarkLog.log(e);			
		}
	}
}
